<?php

// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单结算ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */
quanli_require('module/base/bill/billSearch.class.php');
quanli_require('module/base/bill/billReturn.class.php');

class ajax_orderSettlement {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1:
                    $this->orderSettlementList();
                    break;

                case 2:
                    $this->billOutbound();//订单出仓
                    break;

                case 4:
                    $this->batchReconciliation();//批量对账
                    break;

                case 5:
                    $this->distributionReconciliation();//配送对账查询订单信息
                    break;

                case 100:
                    $this->saveDistributionReconciliation();//配送对账
                    break;

            }
        } else {

            $this->toReturn('参数错误');
        }
    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn($message, $code = 400, $data = '') {

        die(json_encode(array('code' => $code, 'message' => $message, 'data' => $data)));
    }

    /**
     * 查询订单信息
     */
    private function orderSettlementList() {

        global $G_SHOP;
        //查询条件选择了城市、配送站 则根据选择的城市、配送站查询
        if( isset($_REQUEST['deliver_cityid']) && is_numeric($_REQUEST['deliver_cityid']) && isset( $_REQUEST['distribution_id']) && is_numeric($_REQUEST['distribution_id'])){
            $_REQUEST['deliver_cityid'] = $_REQUEST['deliver_cityid'];
            $_REQUEST['distribution_id'] = $_REQUEST['distribution_id'];

            //查询条件选择了城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的配送站查询
        }else if(isset($_REQUEST['deliver_cityid']) && is_numeric($_REQUEST['deliver_cityid']) && !isset( $_REQUEST['distribution_id']) || !is_numeric($_REQUEST['distribution_id']) ){
            $_REQUEST['deliver_cityid'] = $_REQUEST['deliver_cityid'];
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }

            //查询条件没有选择城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的城市、配送站查询
        }else{
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }
        }
        //实例订单类
        $billSearch = new billSearch($G_SHOP->DBCA);

        //查询订单信息
        $bill_array = $billSearch->searchSendBill($_REQUEST);

        $bill_receivable_money = 0;
        //查询满足条件的所有订单信息
        $bill_goods_array = $billSearch->searchSendBillGoods_res( $_REQUEST );
        if( $bill_goods_array ){
            $bill_totalAmount_count = 0;//蛋糕总数
            $bill_receivable_money =0;//应收合计
            foreach( $bill_goods_array as $val){
                $bill_totalAmount_count += $val['bill_totalAmount'];
                $bill_receivable_money += $val['bill_receivable_money'];
            }
        }

        //应收总额四舍五入
        $bill_receivable_money = number_format($bill_receivable_money,2);

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($bill_array) {

            $edit_permission = $G_SHOP->has_permission(20502);

            foreach ($bill_array as &$bill) {

                //订单标识
                if($bill['is_urgent'] == 1){
                    $isUrgent = "加急";
                }else if($bill['is_urgent'] == 2){
                    $isUrgent = "重要";
                }else{
                    $isUrgent = "普通";
                }

                //订单类型
                if($bill['billType'] == 1){
                    $billType = "正常订单";
                }else if($bill['billType'] == 2){
                    $billType = "生日会蛋糕";
                }else if($bill['billType'] == 3){
                    $billType = "市场推广";
                }else if($bill['billType'] == 4){
                    $billType = "其他订单";
                }else if($bill['billType'] == 5){
                    $billType = "补偿订单";
                }else if($bill['billType'] == 6){
                    $billType = "测试订单";
                }else if($bill['billType'] == 7){
                    $billType = "招待赠送";
                }else if($bill['billType'] == 8){
                    $billType = "大客户订单";
                }else{
                    $billType = "试吃订单";
                }

                //订单状态
                if($bill['bill_status'] == 0){
                	$bill_status = "未确认";
                }else if($bill['bill_status'] == 1){
                	$bill_status = "已确认";
                }else if($bill['bill_status'] == 2){
                	$bill_status = "已打印生产单";
                }else if($bill['bill_status'] == 3){
                	$bill_status = "已质检入库";
                }else if($bill['bill_status'] == 4){
                	$bill_status = "已上车";
                }else if($bill['bill_status'] == 5){
                	$bill_status = "已下车";
                }else if($bill['bill_status'] == 6){
                	$bill_status = "已出仓";//暂时没
                }else if($bill['bill_status'] == 7){
                	$bill_status = "已完成";
                }

                //线下配送方式
                if($bill['pay_type'] == 1){
                    $payTypeName = $bill['payTypeName'];
                }else{
                    $payTypeName = "";
                }

                //实例订单退换货类
                $billReturn = new billReturn( $G_SHOP->DBCA );

                $arg_array = array(
                    'bill_no' => $bill['bill_no']
                );

                $bill_info_array = $billReturn->searchBillReturn( $arg_array );

                //退款金额数组
                $bill_return_money_array = array();

                //订单未付金额
                if($bill_info_array){

                    foreach($bill_info_array as $bill_return){

                        if( in_array($bill_return['return_status'],array(2,3,5)) ){

                            $arg_array = array(
                                'return_no' => $bill_return['return_no']
                            );

                            $bill_return_array = $billReturn->searchBillReturnPay( $arg_array );

                            if($bill_return_array){
                                foreach($bill_return_array as $return){
                                    if($return['payTypeName'] == "积分"){
                                        continue;
                                    }
                                    if($return['payTypeName'] == "余额"){
                                        continue;
                                    }
                                    $bill_return_money_array[] = $return['return_pay'];
                                }

                            }

                        }
                    }

                }

				if($bill['bill_receivable_money'] != 0 && $bill['is_reconciliation'] == 0 && ($bill['bill_status'] == 5 || $bill['bill_status'] == 6 || $bill['bill_status'] == 7)){

					//显示订单对账按钮
                    if($bill_info_array){

                        foreach($bill_info_array as $bill_renturn){

                            if($bill_renturn['return_status'] == 1){
                                $operate = "退货未审核";
                            }else{
                                if($G_SHOP->has_permission(20513)){
                                    $operate = '<span style="border: 1px; border-radius: 4px; width: 70px; height: 30px; padding: 3px 9px; background:#3071a9;"><a  href="javascript: void(0);"onclick="orderSettlement.reconciliation(\'' . $bill['bill_code'] . '\' , \''.$bill['bill_no'].'\');"><font style="color:#fff">对账</font></a></span>';
                                }
                            }
                        }
                    }else{
                        if($G_SHOP->has_permission(20513)){
                            $operate = '<span style="border: 1px; border-radius: 4px; width: 70px; height: 30px; padding: 3px 9px; background:#3071a9;"><a  href="javascript: void(0);"onclick="orderSettlement.reconciliation(\'' . $bill['bill_code'] . '\' , \''.$bill['bill_no'].'\');"><font style="color:#fff">对账</font></a></span>';
                        }
                    }
                }else{
                    $operate = "";
                }

                $ReturnKind= "<font face=宋体 color=#13CB00>".$billReturn->GetReturnKind($bill['bill_code'])."</font>";

                if ($edit_permission) {

                    $result_array['rows'][] = array(
                        'id' => $bill['bill_code'],
                        'cell' => array(
                            $operate,
                            '<a href="javascript: void(0);" onclick="orderSettlement.billview(\''.$bill['bill_no'].'\');">'.$bill['bill_code'].'</a>',
                            $isUrgent,
                            $ReturnKind,
                            $billType,
                            $bill_status,
                            $bill['send_date'],
                            $bill['send_start_time'],
                            $bill['send_end_time'],
                            $bill['distribution_name'],
                            $bill['distribution_technicia'],
                            $bill['deliver_city'],
                            $bill['deliver_county'],
                            $bill['deliver_address'],
                            $bill['deliver_name'],
                            $bill['deliver_mobile'],
                            $bill['deliver_phone'],
                            $bill['invoice'] == 1 ? '是' : '否',
                            $bill['bill_totalAmount'],
                            $payTypeName,
                            $bill['bill_receivable_money'],
                            $bill['remark']
                        )
                    );
                } else {

                    $result_array['rows'][] = array(
                        'id' => $bill['bill_code'],
                        'cell' => array(
                            '<a href="javascript: void(0);" onclick="orderSettlement.billview(\''.$bill['bill_no'].'\');">'.$bill['bill_code'].'</a>',
                            $isUrgent,
                            $ReturnKind,
                            $billType,
                            $bill_status,
                            $bill['send_date'],
                            $bill['send_start_time'],
                            $bill['send_end_time'],
                            $bill['distribution_name'],
                            $bill['distribution_technicia'],
                            $bill['deliver_city'],
                            $bill['deliver_county'],
                            $bill['deliver_address'],
                            $bill['deliver_name'],
                            $bill['deliver_mobile'],
                            $bill['deliver_phone'],
                            $bill['invoice'] == 1 ? '是' : '否',
                            $bill['bill_receivable_money'],
                            $payTypeName,
                            $bill['bill_totalMoney'],
                            $bill['remark']
                        )
                    );
                }
            }
        }
        $rows_count = count( $result_array['rows'] ); //计算数据条数

        //蛋糕总数 应收总数 数据组装
        if( $rows_count >= 1 ){
            if ($edit_permission){
                $result_array['rows'][$rows_count] = array(
                    'id' => ' ',
                    'cell' =>array(
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '蛋糕总数：'.$bill_totalAmount_count,
                        '',
                        '应收合计：'.$bill_receivable_money,
                        ''
                    )

                );
            }else{
                $result_array['rows'][$rows_count] = array(
                    'id' => ' ',
                    'cell' =>array(
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '蛋糕总数：'.$bill_totalAmount_count,
                        '',
                        '应收合计：'.$bill_receivable_money,
                        ''
                    )

                );
            }
        }
        echo json_encode($result_array);
    }

    /**
     * 订单出仓
     */
    private function billOutbound() {

        global $G_SHOP;

        if (!isset($_REQUEST['outbound_array']) || !is_array($_REQUEST['outbound_array']) || empty($_REQUEST['outbound_array'])) {
            returnJsonData('系统错误', 400);
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($_REQUEST['outbound_array'] as &$bill_code) {

                //查询订单状态
                $bill_obj = new entity('bill_master');
                $bill_obj->bill_code = $bill_code;

                if (!$G_SHOP->DBCA->fetch($bill_obj)){
                    throw new Exception( $bill_code.'订单信息没找到' , 404);
                }

                if($bill_obj->bill_status != 5){
                    throw new Exception( $bill_code.'订单没有下车或已经出仓' , 404);
                }
                $time = date('Y-m-d H:i:s',time());
                //改变订单状态
                $bill_obj->bill_status = 6;
                $bill_obj->bill_operator = $G_SHOP->currentUserID;
                $bill_obj->bill_operationTime = $time;
                //保存订单状态
                $G_SHOP->DBCA->save( $bill_obj ) ;

            }

            $G_SHOP->DBCA->commit();

            returnJsonData( 'ok',200 );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage() , $e->getCode() );
            } else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }

        }

    }

    /**
     * 订单批量对账
     */
    private function batchReconciliation() {

        global $G_SHOP;

        if (!isset($_REQUEST['batchReconciliation_array']) || !is_array($_REQUEST['batchReconciliation_array']) || empty($_REQUEST['batchReconciliation_array'])) {
            returnJsonData('系统错误', 400);
        }
        quanli_include('module/base/common/quanliLog.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        try {

            $G_SHOP->DBCA->beginTransaction();

            foreach($_REQUEST['batchReconciliation_array'] as &$bill_code) {

                //查询订单状态
                $bill_obj = new entity('bill_master');
                $bill_obj->bill_code = $bill_code;

                if (!$G_SHOP->DBCA->fetch($bill_obj)){
                    throw new Exception($bill_code.'号订单信息没找到', 404);
                }

                //add by sunqiang start

                //实例订单退换货类
                $billReturn = new billReturn( $G_SHOP->DBCA );
                $arg_array = array(
                    'bill_no' => $bill_obj->bill_no
                );
                $bill_info_array = $billReturn->searchBillReturn( $arg_array );
                //退款金额数组
                $bill_return_money_array = array();
                //订单未付金额
                if($bill_info_array){

                    foreach($bill_info_array as $bill_return){

                        if( in_array($bill_return['return_status'],array(2,3,5)) ){

                            $arg_array = array(
                                'return_no' => $bill_return['return_no']
                            );

                            $bill_return_array = $billReturn->searchBillReturnPay( $arg_array );

                            if($bill_return_array){
                                foreach($bill_return_array as $return){
                                    if($return['payTypeName'] == "积分"){
                                        continue;
                                    }
                                    if($return['payTypeName'] == "余额"){
                                        continue;
                                    }
                                    $bill_return_money_array[] = $return['return_pay'];
                                }

                            }

                        }
                    }

                }
                //退货总金额
                //$bill_return_money = array_sum($bill_return_money_array);
                //$bill_tmp_money = $bill_obj->bill_receivable_money - $bill_return_money;

                //if(intval($bill_obj->bill_receivable_money) > 0 && $bill_tmp_money > 0 ){
                    //throw new Exception($bill_code.'号订单没有付款完成', 404);
                //}

                //add by sunqiang end

                //上面的逻辑部分退货的情况下有误，条件改为：应收金额>0 add by allen.qiang 2015-06-08
                if(intval($bill_obj->bill_receivable_money) > 0 ){
                    throw new Exception($bill_code.'号订单没有付款完成', 404);
                }

                $bill_no = $bill_obj->bill_no;
                //改变订单状态
                $bill_obj->is_reconciliation = 1;
                $bill_obj->bill_status = 7;

                //保存订单状态
                $G_SHOP->DBCA->save( $bill_obj ) ;

                //保存日志
                $log_array = array(
                    'logCategoryID' => 1,
                    'logItem' => $bill_no,
                    'extend_1' => '订单已结算',
                    'extend_2' => '已结算',
                    'extend_5' => 7,
                    //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --start
                    //'operator' => $G_SHOP->currentUserID
                    'operator' => $G_SHOP->currentUserName
                    //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --end
                );
               $quanliLog->saveLogInfo( $log_array );

                //已完成的订单表
                $bill_finish_obj = new entity('bill_finish');
                $bill_finish_obj->bill_no = $bill_no;
                $bill_finish_obj->creator = $G_SHOP->currentUserID;
                //把完成对账的订单号存入bill_finish表中
                $G_SHOP->DBCA->save( $bill_finish_obj ) ;

                /*=======================================================
                 * 保存订单轨迹 start
                 * ======================================================
                 */
                quanli_include('module/base/bill/billEdit.class.php');

                $operator = $G_SHOP->currentUserID;
                $content = '您的订单已结算';

                $billEdit = new billEdit( $G_SHOP->DBCA);
                $billTrace = $billEdit->addBillTrace( $bill_no, $operator, $content );
                if ( !$billTrace ){
                    throw new Exception( '订单轨迹保存失败', 400);
                }

                /*=======================================================
                 * 保存订单轨迹 end
                 * ======================================================
                 */


            }

            $G_SHOP->DBCA->commit();

            returnJsonData( 'ok',200 );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                returnJsonData(  $e->getMessage() ,$e->getCode());
            } else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }

        }

    }

    /**
     * 订单配送对账信息查询
     */
    private function distributionReconciliation() {

        global $G_SHOP;


        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])) {
            returnJsonData('系统错误', 400);

        }


        $arg_array =array(
            'bill_no' => $_REQUEST['bill_no']
        );

        //实例订单类
        $billSearch = new billSearch($G_SHOP->DBCA);


        //查询订单信息
        $bill_array = $billSearch->searchSendBill($arg_array);

        //查询订单支付信息
        $pay_array = $billSearch->searchBillPay($_REQUEST);

        //实例订单退换货类
        $billReturn = new billReturn( $G_SHOP->DBCA );

        $bill_info_array = $billReturn->searchBillReturn( $arg_array );

//        $return_pay_array = array();
//        if($bill_info_array){
//            foreach($bill_info_array as $bill_return){
//                if($bill_return['return_status'] != 4){
//                    $arg_array = array (
//                        'return_no'=> $bill_return['return_no']
//                    );
//                    $bill_return_pay_array = $billReturn->searchBillReturnPay( $arg_array );
//
//                    foreach($bill_return_pay_array as $return){
//                        $return_pay_array[] = $return['payTypeName'];
//                    }
//                }
//            }
//        }

        if($pay_array){
            foreach($pay_array as $key => $pay){
//                if($pay['payTypeName'] == "积分" && in_array($pay['payTypeName'],$return_pay_array)){
//                    continue;
//                }
//                if($pay['payTypeName'] == "余额" && in_array($pay['payTypeName'],$return_pay_array)){
//                    continue;
//                }
                $bill_array[0]['pay_data'][$key]['payment_method_type'] = $pay['payment_method_type'];
                $bill_array[0]['pay_data'][$key]['payment_method_name'] = $pay['payment_method_name'];
                $bill_array[0]['pay_data'][$key]['payment_method_id'] = $pay['payment_method_id'];
                $bill_array[0]['pay_data'][$key]['bill_pay_no'] = $pay['bill_pay_no'];
                $bill_array[0]['pay_data'][$key]['type'] = $pay['type'];
                if($pay['payTypeID'] == 3){//积分
                    $bill_array[0]['pay_data'][$key]['pay_amount'] = sprintf("%.2f",$pay['pay_amount']/100);
                }else{
                    $bill_array[0]['pay_data'][$key]['pay_amount'] = $pay['pay_amount'];
                }
                $bill_array[0]['pay_data'][$key]['payTypeID'] = $pay['payTypeID'];
                $bill_array[0]['pay_data'][$key]['payTypeName'] = $pay['payTypeName'];
                if($pay['type'] == 2){
                    $bill_array[0]['pay_data'][$key]['pay_online_amount'] = $pay['pay_amount'] - $bill_array[0]['bill_online_money'];
                }
            }
        }

        if(!$bill_array){
            returnJsonData('订单不存在');
        }



        //退款金额数组
        $bill_return_money_array = array();
        //订单未付金额
        if($bill_info_array){

            foreach($bill_info_array as $bill_return){

                if($bill_return['return_status'] == 2 || $bill_return['return_status'] == 3){

                    $arg_array = array(
                        'return_no' => $bill_return['return_no']
                    );

                    $bill_return_array = $billReturn->searchBillReturnPay( $arg_array );

                    if($bill_return_array){
                        foreach($bill_return_array as $return){
                            if($return['payTypeName'] == "积分"){
                                continue;
                            }
                            if($return['payTypeName'] == "余额"){
                                continue;
                            }
                            //$bill_return_money_array[] = $return['return_pay'];
                        }

                    }

                }
            }
                //退货总金额
                //$bill_return_money = array_sum($bill_return_money_array);

                //$bill_array[0]['bill_receivable_money'] = $bill_array[0]['bill_receivable_money'] - $bill_return_money;
                $bill_array[0]['bill_receivable_money'] = $bill_array[0]['bill_receivable_money'];

        }

        returnJsonData('ok', 200, $bill_array[0]);

    }

    /**
     * 订单配送对账操作
     */
    private function saveDistributionReconciliation() {

        global $G_SHOP;

        //验证
        if(!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['pay_type'])){
            returnJsonData('该订单未支付完成，无法结算');
        }

        if(!isset($_REQUEST['get_money']))
            returnJsonData( '请输入付款金额' , 400 );

        //收款金额
        $collection = array_sum($_REQUEST['get_money']);

        quanli_include('module/base/common/quanliLog.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        $bill_no = $_REQUEST['bill_no'];

        //检查订单信息是否存在

        $bill_obj = new entity('bill_master');
        $bill_obj->bill_no = $bill_no;
        if (!$G_SHOP->DBCA->fetch($bill_obj)){
            returnJsonData( '订单信息没找到', 404 );
        }

        //实例订单退换货类
        $billReturn = new billReturn( $G_SHOP->DBCA );

        $arg_array = array(
            'bill_no' => $_REQUEST['bill_no']
        );

        //查询订单是否有退货未审核
        $bill_info_array = $billReturn->searchBillReturn( $arg_array );

        if($bill_info_array){

            foreach($bill_info_array as $return_obj){

                if($return_obj['return_status'] == 1){
                    returnJsonData( '订单退货未审核，不能对账', 404 );
                    break;
                }

                if($return_obj['return_status'] == 4){
                    continue;
                }
            }
        }

        //应收金额
        $not_pay_money = $bill_obj->bill_receivable_money;

        //判断未付金额是否等于实收金额$a < $b+0.01 && $a > $b-0.01
        if($not_pay_money > $collection+0.01 || $not_pay_money < $collection-0.01)
            returnJsonData( '付款金额数目不对' , 400 );

        try{

            //开启事务
            $G_SHOP->DBCA->beginTransaction();

            foreach($_REQUEST['billPayNo'] as $key=> $bill_pay_no){

                $bill_distribution_obj = new entity('bill_distribution_checking');

                $bill_pay_obj = new entity('bill_pay');
                $bill_pay_obj->bill_pay_no = $bill_pay_no;

                if($bill_pay_obj->bill_pay_no != ""){

                    if ($G_SHOP->DBCA->fetch($bill_pay_obj)){
                        $bill_distribution_obj->bill_no = $bill_no;
                        $bill_distribution_obj->creator = $G_SHOP->currentUserID;
                        $bill_distribution_obj->payTypeID = $bill_pay_obj->payTypeID;
                        $bill_distribution_obj->payTypeName = $bill_pay_obj->payTypeName;
                        $bill_distribution_obj->type = $bill_pay_obj->type;
                        $bill_distribution_obj->pay_amount = $bill_pay_obj->pay_amount;
                        $bill_distribution_obj->deduct_amount = $bill_pay_obj->deduct_amount;
                        $bill_distribution_obj->pay_code = $bill_pay_obj->pay_code;
                        $bill_distribution_obj->pay_time = $bill_pay_obj->pay_time;
                        $bill_distribution_obj->paid_confirm_status = $bill_pay_obj->paid_confirm_status;
                        $bill_distribution_obj->paid_confirmer = $bill_pay_obj->paid_confirmer;
                        $bill_distribution_obj->paid_confirm_time = $bill_pay_obj->paid_confirm_time;
                        $bill_distribution_obj->payment_method_id = $bill_pay_obj->payment_method_id;
                        $bill_distribution_obj->payment_method_name = $bill_pay_obj->payment_method_name;
                        $bill_distribution_obj->payment_method_type = $bill_pay_obj->payment_method_type;

                        if($bill_pay_obj->type == 1 && $bill_pay_obj->payment_method_type == 2){
                            $bill_distribution_obj->pos_serial_number = isset($_REQUEST['posSerialNumber'][$key]) ? trim($_REQUEST['posSerialNumber'][$key]) : "";
                            $bill_distribution_obj->pos_device_number = isset($_REQUEST['posCut'][$key]) ? trim($_REQUEST['posCut'][$key]) : "";
                        }
                        if($bill_pay_obj->type == 1){
                            $bill_distribution_obj->receipt_amount = isset($_REQUEST['get_money'][$key]) ? $_REQUEST['get_money'][$key] : 0;
                            $bill_distribution_obj->cash_card_number = "";
                        }
                        if($bill_pay_obj->type == 2){
                            $bill_distribution_obj->receipt_amount = isset($_REQUEST['get_money'][$key]) ? $_REQUEST['get_money'][$key] : 0;
                            $bill_distribution_obj->cash_card_number = "";
                        }
                    }
                }else{
                    $bill_distribution_obj->bill_no = $bill_no;
                    $bill_distribution_obj->creator = $G_SHOP->currentUserID;
                    $bill_distribution_obj->payTypeID = 1;
                    $bill_distribution_obj->payTypeName = "货到付款";
                    $bill_distribution_obj->type = 1;
                    $bill_distribution_obj->pay_amount = isset($_REQUEST['get_money'][$key]) ? $_REQUEST['get_money'][$key] : 0;
                    $bill_distribution_obj->deduct_amount = 0;
                    $bill_distribution_obj->pay_code = "";
                    $bill_distribution_obj->pay_time = "";
                    $bill_distribution_obj->paid_confirm_status = "";
                    $bill_distribution_obj->paid_confirmer = "";
                    $bill_distribution_obj->paid_confirm_time = "";
                    $bill_distribution_obj->payment_method_id = isset($_REQUEST['type'][$key]) ? $_REQUEST['type'][$key] : "";;
                    $bill_distribution_obj->payment_method_name =  isset($_REQUEST['pay_ment'][$key]) ? $_REQUEST['pay_ment'][$key] : "";
                    if($_REQUEST['pay_type'][$key] == 1){
                        $bill_distribution_obj->payment_method_type = 1;
                    }else{
                        $bill_distribution_obj->payment_method_type = 2;
                    }
                    $bill_distribution_obj->pos_serial_number = isset($_REQUEST['posSerialNumber'][$key]) ? trim($_REQUEST['posSerialNumber'][$key]) : "";
                    $bill_distribution_obj->pos_device_number = isset($_REQUEST['posCut'][$key]) ? trim($_REQUEST['posCut'][$key]) : "";
                    $bill_distribution_obj->receipt_amount = isset($_REQUEST['get_money'][$key]) ? $_REQUEST['get_money'][$key] : 0;
                    $bill_distribution_obj->cash_card_number = "";
                }

                if($G_SHOP->DBCA->fetch($bill_pay_obj)){

                    if($bill_pay_obj->type == 7){

                        $bill_distribution_obj->pos_serial_number = "";
                        $bill_distribution_obj->pos_device_number = "";
                        $bill_distribution_obj->receipt_amount = 0;
                        $bill_distribution_obj->cash_card_number = isset($_REQUEST['casCardNumber']) ? $_REQUEST['casCardNumber'] : "";

                    }

                    if($bill_pay_obj->type == 2){

                        $bill_distribution_obj->pos_serial_number =  "";
                        $bill_distribution_obj->pos_device_number =  "";
                        $bill_distribution_obj->receipt_amount = $bill_obj->bill_online_money;
                        $bill_distribution_obj->cash_card_number = "";
                    }


                    if(!in_array($bill_pay_obj->type,array(1,2,7))){
                        $bill_distribution_obj->pos_serial_number =  "";
                        $bill_distribution_obj->pos_device_number =  "";
                        $bill_distribution_obj->receipt_amount = $bill_pay_obj->pay_amount;
                        $bill_distribution_obj->cash_card_number = "";
                    }

                }
                //保存配送对账表
                $G_SHOP->DBCA->save( $bill_distribution_obj );

                $log_array = array(
                    'logCategoryID' => 1,
                    'logItem' => $bill_no,
                    'extend_1' => '订单已结算',
                    'extend_2' => $bill_distribution_obj->payTypeName.'  ' .$bill_distribution_obj->payment_method_name .''.$bill_distribution_obj->receipt_amount.'元 已结算',
                    'extend_5' => 7,
                    //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --start
                    //'operator' => $G_SHOP->currentUserID
                    'operator' => $G_SHOP->currentUserName
                    //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --end
                );

                $quanliLog->saveLogInfo( $log_array );
            }

            //保存订单结算时状态，应收金额到订单结算临时表
            $bill_temp_obj = new entity('bill_distribution_temp');
            $bill_temp_obj->creator = $G_SHOP->currentUserID;
            $bill_temp_obj->bill_no = $bill_no;
            $bill_temp_obj->bill_receivable_money = $bill_obj->bill_receivable_money;
            $bill_temp_obj->bill_received_money = $bill_obj->bill_received_money;
            $bill_temp_obj->bill_status = $bill_obj->bill_status;
            $G_SHOP->DBCA->save( $bill_temp_obj );

            //修改订单主表配送对账字段，保存配送对账备注
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;

            if ($G_SHOP->DBCA->fetch($bill_master)){
                $bill_master->is_reconciliation = 1;
                $bill_master->bill_status = 7;
                $bill_master->bill_received_money += $collection;
                $bill_master->bill_receivable_money -= $collection;



                if(($bill_obj->bill_receivable_money - $collection) <= 0){
                    $bill_master->pay_status = 1;
                }

                $bill_master->bill_checking_remark = isset($_REQUEST['bill_checking_remark']) ? $_REQUEST['bill_checking_remark'] : "";

                $G_SHOP->DBCA->save( $bill_master );
            }


            //已完成的订单表
            $bill_finish_obj = new entity('bill_finish');
            $bill_finish_obj->bill_no = $bill_no;
            $bill_finish_obj->creator = $G_SHOP->currentUserID;
            //把完成对账的订单号存入bill_finish表中
            $G_SHOP->DBCA->save( $bill_finish_obj );

            /*=======================================================
           * 保存订单轨迹 start
           * ======================================================
           */
            quanli_include('module/base/bill/billEdit.class.php');

            $operator = $G_SHOP->currentUserID;
            $content = '您的订单已结算';

            $billEdit = new billEdit( $G_SHOP->DBCA);
            $billTrace = $billEdit->addBillTrace( $bill_no, $operator, $content );
            if ( !$billTrace ){
                throw new Exception( '订单轨迹保存失败', 400);
            }

            /*=======================================================
             * 保存订单轨迹 end
             * ======================================================
             */
            $G_SHOP->DBCA->commit();
            returnJsonData( '对账成功' , 200 );

        }catch (Exception $e) {
            $G_SHOP->DBCA->rollBack();
            if ($e->getCode() > 0)
                returnJsonData( $e->getCode(), $e->getMessage() );
            else {
                error_log($e->getMessage());
                returnJsonData( '系统错误'.$e->getMessage(), 500 );
            }
        }

    }

}
